<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import storage from "../../../storage/storage";
import EventBus from "../../../utils/evenBus/evenBus";
import { groupChats } from "../../../utils/https/api"
let input = ref("");
//实例
let ws = null;

//每个窗口 id
let userId = ref("");

//消息列表
let msgList = ref([]);

//聊天窗口dom
let box = ref(null);

//房间名称
let roomName = ref("");

//加入的房间号
let inRoomId = ref("");

let userInfo = ref({});

//房间信息
let roomInfo = ref({});

//本地ip地址
let ip = "";

let emit = defineEmits(["successRoom", "delSuccessRoom", "inSuccessRoom"]);

let show = (e) => {
  console.log("获取的数据", e);
  roomName.value = e.roomName;
  let data = {
    userId: userId.value,
    roomId: e.roomId * 1,
    roomName: roomName.value,
    message: `用户${userId.value}创建了群聊房间`,
    in: true,
    operate: 0,
    created: userId.value,
  };
  ws.send(JSON.stringify(data));
};
onMounted(() => {
  EventBus.on("roomInfo", (res) => {
    roomInfo.value = res;
    groupChatsList()
  });
  userInfo.value = JSON.parse(storage.getCookies("userInfo"));
  ip = import.meta.env.VITE_SOCKETURL;
  newSocket();
});

//获取当前房间群聊成员
let groupChatsList=()=>{
  groupChats({roomId:roomInfo.value.roomId}).then(res=>{
    
  })
}

let newSocket = () => {
  ws = new WebSocket(`ws://${ip}:3000?userId=` + userInfo.value.id);
  ws.addEventListener("open", (e) => {
    console.log("正在连接中...", e);
    if (e.currentTarget.readyState === 1) {
      console.log("服务已连接");
    }
  });

  ws.addEventListener("message", (e) => {
    console.log(e);
    let data = JSON.parse(e.data);

    //创建房间消息提示
    if (data.operate === 0) {
      if (data.created) {
        successRoomTrue();
        ElMessage.success(data.message);
      } else {
        ElMessage.error(data.message);
      }
    }

    //加入房间
    if (data.operate === 1) {
      if (!data.isExist) {
        ElMessage.error(data.message);
      } else {
        roomId.value = data.roomId;
        if (userId.value !== data.userId) {
          msgList.value.push(data);
        } else {
          roomId.value = inRoomId.value;
          ElMessage.success(data.message);
          emit("inSuccessRoom", {
            roomName: data.roomName,
            roomId: data.roomId,
          });
        }
      }
    }

    //聊天
    if (data.operate === 2) {
      if (userId.value !== data.userId) {
        msgList.value.push(data);
      }
    }

    //删除房间
    if (data.operate === 3) {
      if (!data.delStauts) {
        emit("delSuccessRoom", data);
      } else {
        ElMessage.error(data.message);
      }
    }
  });

  ws.addEventListener("close", (e) => {
    console.log("断开连接", e);
  });

  ws.addEventListener("error", (e) => {
    console.log("异常", e);
  });
};

//发送消息
let sendMsg = () => {
  if (!roomInfo.value.roomId)
    return ElMessage.error("请先创建群聊房间或加入群聊房间");
  if (!input.value) return;
  let data = {
    userId: userInfo.value.id,
    message: input.value,
    in: false,
    operate: 2,
    roomId: roomInfo.value.roomId,
  };
  msgList.value.push(data);
  ws.send(JSON.stringify(data));
  input.value = "";
};

let send = (e) => {
  let keyCode = e.keyCode;
  if (!input.value) return;
  if (keyCode == 13) {
    let data = {
      userId: userInfo.value.id,
      message: input.value,
      in: false,
      operate: 2,
      roomId: roomInfo.value.roomId,
    };
    msgList.value.push(data);
    ws.send(JSON.stringify(data));
    input.value = "";
  }
};
//加入群聊
let inRoom = () => {
  if (!inRoomId.value) return ElMessage.error("请输入房间号");
  let data = {
    userId: userInfo.value.id,
    roomId: inRoomId.value,
    message: "",
    in: true,
    operate: 1,
  };
  ws.send(JSON.stringify(data));
};

let successRoomTrue = () => {
  emit("successRoom", { roomName: roomName.value, roomId: roomId.value * 1 });
};

let handoffRoom = (e) => {
  roomName.value = e.roomName;
  roomId.value = e.roomId * 1;
};

let delRoom = (e) => {
  let data = {
    roomId: e.roomId,
    userId: userId.value,
    operate: 3,
  };
  ws.send(JSON.stringify(data));
};

defineExpose({ show, handoffRoom, delRoom });
</script>

<template>
  <div class="right_box">
    <div class="addRoom">
      <el-input
        v-model="inRoomId"
        style="width: 43%"
        placeholder="请输入房间号" />
      <el-button type="primary" @click="inRoom">加入群聊房间</el-button>
    </div>
    <div class="home_box" ref="box">
      <div
        v-for="(t, i) in msgList"
        :key="i"
        :class="userInfo.id == t.userId ? 'myStyle' : 'thStyle'">
        <div v-if="!t.in" class="hasMessage">
          <div v-if="userInfo.id == t.userId" class="message">{{ t.message }}</div>
          <div class="user">{{ t.userId }}</div>
          <div v-if="userInfo.id != t.userId" class="message">{{ t.message }}</div>
        </div>
        <div v-if="t.in" class="prompt">{{ t.message }}</div>
      </div>
    </div>
    <div class="inputBox">
      <el-input
        v-model="input"
        style="width: 90%"
        placeholder="Please input"
        @keydown="send" />
      <el-button type="primary" @click="sendMsg">发送</el-button>
    </div>
  </div>
</template>

<style scoped>
.right_box {
  background: linear-gradient(135deg, #ffd26f, #3677ff);
  box-shadow: 0 0 10px #000;
  border-radius: 10px;
  padding: 10px;
}
.addRoom {
  display: flex;
  margin: 20px 0;
}

.home_box {
  height: 50vh;
  overflow-y: scroll;
  border-radius: 10px;
  scrollbar-width: none;
  padding: 20px;
  width: 50%;
  background: #e5bb62;
  box-shadow: 0 0 10px #000;
  box-sizing: border-box;
}
.inputBox {
  margin-top: 20px;
  width: 50%;
}

.myStyle {
  display: flex;
  justify-content: flex-end;
  margin: 10px 0;
}

.thStyle {
  display: flex;
  margin: 10px 0;
}

.user {
  width: 40px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 50%;
  background: #000;
  color: #fff;
  font-size: 14px;
  margin: 0 10px;
}

.prompt {
  display: flex;
  justify-content: center;
  color: #000;
  font-size: 12px;
}

.hasMessage {
  display: flex;
  align-items: center;
}
.message:nth-of-type(1) {
  color: #000;
  background: #c7ecee;
  padding: 5px 10px;
  font-size: 12px;
  border-radius: 10px 0 10px 0;
}
.message:nth-of-type(2) {
  color: #000;
  background: #c7ecee;
  padding: 5px 10px;
  font-size: 12px;
  border-radius: 0px 10px 0px 10px;
}
</style>
